package com.google.code.synchronized_player;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;

public class SelectorActivity extends Activity {
	private List<String> directoryEntries = new ArrayList<String>();
	private ArrayAdapter<String> directoryList;
	private ListView list;
	private File currentDirectory = new File("/");
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selector);
        directoryList = new ArrayAdapter<String> (this, R.layout.file_item, this.directoryEntries);
        list = (ListView)this.findViewById(R.id.files);
        list.setAdapter(directoryList);
        browse();
    }
    
    public void browse() {
    	if(!currentDirectory.isDirectory()) {
    		Intent returnIntent = new Intent();
    		returnIntent.putExtra("path", currentDirectory.getAbsolutePath());
    		setResult(RESULT_OK, returnIntent);     
    		finish();
    		return;
    	}
    	directoryEntries.clear();
    	if(currentDirectory.getParent() != null) {
    		directoryEntries.add("..");
    	}
    	File files[] = currentDirectory.listFiles();
    	for(File file: files) {
    		directoryEntries.add(file.getAbsolutePath());
    	}
    	directoryList.notifyDataSetChanged();
        list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String selectedFileString = directoryEntries.get(position);
				if(selectedFileString.equals("..")) {
					if(currentDirectory.getParent() != null) {
						currentDirectory = currentDirectory.getParentFile();
					}
				} else {
					currentDirectory = new File(selectedFileString);
				}
				browse();
			}
        });
    }
    
    public void onDestroy() {
    	Intent returnIntent = new Intent();
		returnIntent.putExtra("path", "");
		setResult(RESULT_OK, returnIntent); 
    	super.onDestroy();
    }
}
